package com.mes.biz.service.impl;

import java.math.BigDecimal;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.util.StringUtil;
import com.mes.biz.domain.*;
import com.mes.biz.domain.vo.ConvertRatioNumberUnit;
import com.mes.biz.mapper.BizInventoryOpeningDetailsMapper;
import com.mes.biz.service.*;
import com.mes.common.constant.BizConstants;
import com.mes.common.core.domain.BaseEntity;
import com.mes.common.core.service.BaseServiceImpl;
import com.mes.common.exception.BizException;
import com.mes.common.utils.DateUtils;
import com.mes.common.utils.SecurityUtils;
import com.mes.common.utils.StringUtils;
import com.mes.system.strategy.AutoCodeUtil;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.pagehelper.PageInfo;
import com.mes.biz.mapper.BizInventoryOpeningMapper;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 库存期初Service业务层处理
 * @author wy
 * @email wy
 * @date 2023-06-08
 */
@Service
@Transactional(readOnly = true)
public class BizInventoryOpeningServiceImpl extends BaseServiceImpl<BizInventoryOpeningMapper, BizInventoryOpening> implements BizInventoryOpeningService {

    private static final Logger log = LoggerFactory.getLogger(BizInventoryOpeningServiceImpl.class);

    @Resource
    private AutoCodeUtil autoCodeUtil;

    @Resource
    private BizInventoryOpeningDetailsService bizInventoryOpeningDetailsService;

    @Resource
    private BizInventoryOpeningDetailsMapper bizInventoryOpeningDetailsMapper;

    @Resource
    private BizProductInventoryService bizProductInventoryService;

    @Resource
    private BizProductService bizProductService;

    @Resource
    private BizProductInventoryBookService bizProductInventoryBookService;

    /**
     * 获取单条数据
     * @param bizInventoryOpening 库存期初
     * @return 库存期初
     */
    @Override
    public BizInventoryOpening get(BizInventoryOpening bizInventoryOpening) {
        BizInventoryOpening dto = super.get(bizInventoryOpening);
        return dto;
    }

    /**
     * 获取单条数据
     * @param id 库存期初id
     * @return 库存期初
     */
    @Override
    public BizInventoryOpening get(String id) {
        BizInventoryOpening dto = super.get(id);
        return dto;
    }

    /**
     * 查询库存期初列表
     * @param bizInventoryOpening 库存期初
     * @return 库存期初
     */
    @Override
    public List<BizInventoryOpening> findList(BizInventoryOpening bizInventoryOpening) {
		List<BizInventoryOpening> bizInventoryOpeningList = super.findList(bizInventoryOpening);
        return bizInventoryOpeningList;
    }

    /**
     * 分页查询库存期初列表
     * @param bizInventoryOpening 库存期初
     * @return 库存期初
     */
    @Override
    public PageInfo<BizInventoryOpening> findPage(BizInventoryOpening bizInventoryOpening) {
		PageInfo<BizInventoryOpening> page = super.findPage(bizInventoryOpening);
        return page;
    }

    /**
     * 保存库存期初
     * @param bizInventoryOpening
     * @return 结果
     */
    @Override
    public boolean save(BizInventoryOpening bizInventoryOpening) {
        return super.save(bizInventoryOpening);
    }

    /**
     * 删除库存期初信息
     * @param bizInventoryOpening
     * @return 结果
     */
    @Override
    public boolean remove(BizInventoryOpening bizInventoryOpening) {
        return super.remove(bizInventoryOpening);
    }

    /**
     * 批量删除库存期初
     * @param ids 需要删除的库存期初ID
     * @return 结果
     */
    @Transactional(readOnly = false)
    @Override
    public int deleteBizInventoryOpeningByIds(String[] ids) {
        return mapper.deleteBizInventoryOpeningByIds(ids, BaseEntity.DEL_FLAG_DELETE);
    }

    @Override
    @Transactional(readOnly = false)
    public Boolean insertBizInventoryOpening(BizInventoryOpening bizInventoryOpening) {
        String code = autoCodeUtil.genSerialCode("INVENTORY_OPENING_CODE",null);
        bizInventoryOpening.setOrderNo(code);
        String tenantId = SecurityUtils.getTenantId();
        bizInventoryOpening.setTenantId(tenantId);
        bizInventoryOpening.setStatus(1);
        boolean res = save(bizInventoryOpening);
        if(res) {
            for (BizInventoryOpeningDetails details : bizInventoryOpening.getDetailsList()) {
                BizInventoryOpeningDetails inventoryOpeningDetails = new BizInventoryOpeningDetails();
                inventoryOpeningDetails.setProductCode(details.getProductCode());
                inventoryOpeningDetails.setTotalAmount(details.getTotalAmount());
                inventoryOpeningDetails.setUnitPrice(details.getUnitPrice());
                inventoryOpeningDetails.setUnit(details.getUnit());
                inventoryOpeningDetails.setSpaceId(details.getSpaceId());
                inventoryOpeningDetails.setProductNumber(details.getProductNumber());
                inventoryOpeningDetails.setOrderNo(bizInventoryOpening.getOrderNo());
                inventoryOpeningDetails.setTenantId(tenantId);
                inventoryOpeningDetails.setRemark(details.getRemark());
                bizInventoryOpeningDetailsService.save(inventoryOpeningDetails);
            }
        }
        return res;

    }

    @Override
    @Transactional(readOnly = false)
    public Boolean updateBizInventoryOpening(BizInventoryOpening bizInventoryOpening) {
        boolean res = save(bizInventoryOpening);
        if( bizInventoryOpening.getDetailsList().size()>0) {
            bizInventoryOpeningDetailsMapper.deleteBizInventoryOpeningDetailsByOrderNo(bizInventoryOpening.getOrderNo(),"1");
            String tenantId = SecurityUtils.getTenantId();
            for (BizInventoryOpeningDetails details : bizInventoryOpening.getDetailsList()) {
                BizInventoryOpeningDetails inventoryOpeningDetails = new BizInventoryOpeningDetails();
                inventoryOpeningDetails.setProductCode(details.getProductCode());
                inventoryOpeningDetails.setTotalAmount(details.getTotalAmount());
                inventoryOpeningDetails.setTotalAmount(details.getTotalAmount());
                inventoryOpeningDetails.setUnitPrice(details.getUnitPrice());
                inventoryOpeningDetails.setUnit(details.getUnit());
                inventoryOpeningDetails.setSpaceId(details.getSpaceId());
                inventoryOpeningDetails.setProductNumber(details.getProductNumber());
                inventoryOpeningDetails.setOrderNo(bizInventoryOpening.getOrderNo());
                inventoryOpeningDetails.setTenantId(tenantId);
                inventoryOpeningDetails.setRemark(details.getRemark());
                bizInventoryOpeningDetailsService.save(inventoryOpeningDetails);
            }
        }
        return res;
    }

    @Override
    @Transactional(readOnly = false)
    public Boolean auditBizInventoryOpening(String id) {
        BizInventoryOpening bizInventoryOpening = super.get(id);
        bizInventoryOpening.setStatus(2);
        mapper.update(bizInventoryOpening);
        //查询采购单明细信息
        BizInventoryOpeningDetails paramDetail = new BizInventoryOpeningDetails();
        paramDetail.setOrderNo(bizInventoryOpening.getOrderNo());
        List<BizInventoryOpeningDetails> list = bizInventoryOpeningDetailsService.findList(paramDetail);
        for(BizInventoryOpeningDetails details:list) {
            if (StringUtils.isEmpty(details.getSpaceId())){
                throw new BizException("审核通过时，明细库位不能为空");
            }
            if (StringUtil.isEmpty(details.getUnit())){
                throw new BizException("单位不能为空!");
            }
//            if (details.getProductNumber() == null){
//                throw new BizException("数量不能为空！");
//            }
            if(details.getProductNumber()==null){
                return false;
            }
            BizProduct bizProduct = bizProductService.getBizProductByProductCode(details.getProductCode());
            BizProductInventory bizProductInventory = bizProductInventoryService.getByProductIdAndSpaceId(bizProduct.getId(),details.getSpaceId());
            //计算基础数量
            BigDecimal basicNumber = ConvertRatioNumberUnit.convertRatio(details.getProductNumber(), details.getUnit(), bizProduct);
            if(bizProductInventory==null) {
                bizProductInventory = new BizProductInventory();
                bizProductInventory.setProductId(bizProduct.getId());
                bizProductInventory.setAmount(details.getTotalAmount());
                bizProductInventory.setNumber(basicNumber);
                bizProductInventory.setPrice(details.getUnitPrice());
                bizProductInventory.setSpaceId(details.getSpaceId());
                bizProductInventory.setWarehouseId(bizInventoryOpening.getWarehouseId());
                bizProductInventory.setTenantId(SecurityUtils.getTenantId());
                bizProductInventory.setAssistNumberA(bizProductInventory.getNumber().multiply(bizProduct.getConvertRatioA()).setScale(3,BigDecimal.ROUND_HALF_UP));
                bizProductInventory.setAssistNumberB(bizProductInventory.getNumber().multiply(bizProduct.getConvertRatioB()).setScale(3,BigDecimal.ROUND_HALF_UP));
                bizProductInventory.setOpeningNumber(basicNumber);
                bizProductInventoryService.save(bizProductInventory);
            } else {
                BigDecimal number = bizProductInventory.getNumber() == null ? BigDecimal.ZERO : bizProductInventory.getNumber();
                BigDecimal productNumber = number.add(basicNumber);
                BigDecimal amount = bizProductInventory.getAmount()  == null ? BigDecimal.ZERO : bizProductInventory.getAmount();
                BigDecimal totalAmount = amount.add(details.getTotalAmount());
                bizProductInventory.setAmount(totalAmount);
                if (totalAmount.compareTo(BigDecimal.ZERO)>0){
                    bizProductInventory.setPrice(totalAmount.divide(productNumber,3,BigDecimal.ROUND_HALF_UP));
                }else {
                    bizProductInventory.setPrice(BigDecimal.ZERO);
                }
                bizProductInventory.setProductId(bizProduct.getId());
                bizProductInventory.setNumber(bizProductInventory.getNumber().add(basicNumber));
                bizProductInventory.setAssistNumberA(bizProductInventory.getNumber().multiply(bizProduct.getConvertRatioA()).setScale(3,BigDecimal.ROUND_HALF_UP));
                bizProductInventory.setAssistNumberB(bizProductInventory.getNumber().multiply(bizProduct.getConvertRatioB()).setScale(3,BigDecimal.ROUND_HALF_UP));
                if (bizProductInventory.getOpeningNumber() != null && bizProductInventory.getOpeningNumber().compareTo(BigDecimal.ZERO)>0){
                    bizProductInventory.setOpeningNumber(bizProductInventory.getOpeningNumber().add(basicNumber));
                }else {
                    bizProductInventory.setOpeningNumber(basicNumber);
                }
                bizProductInventoryService.update(bizProductInventory);
            }
            //保存产品库存台账
            BizProductInventoryBook productInventoryBook = new BizProductInventoryBook();
            productInventoryBook.setBizDate(DateUtils.getNowDate());
            productInventoryBook.setAmount(details.getTotalAmount());
            productInventoryBook.setOrderNumber("期初库存");
            productInventoryBook.setAssistUnitA(bizProductInventory.getAssistUnitA());
            productInventoryBook.setAssistUnitB(bizProductInventory.getAssistUnitB());
            productInventoryBook.setSpaceId(details.getSpaceId());
            productInventoryBook.setWarehouseId(bizInventoryOpening.getWarehouseId());
            productInventoryBook.setInventoryId(bizProductInventory.getId());
            productInventoryBook.setNumber(basicNumber);
            productInventoryBook.setAssistNumberB(basicNumber.multiply(bizProduct.getConvertRatioB()).setScale(3,BigDecimal.ROUND_HALF_UP));
            productInventoryBook.setAssistNumberA(basicNumber.multiply(bizProduct.getConvertRatioA()).setScale(3,BigDecimal.ROUND_HALF_UP));
            productInventoryBook.setOrderNumber(bizInventoryOpening.getOrderNo());
            productInventoryBook.setOrderType(BizConstants.ORDER_TYPE_OPENING);
            productInventoryBook.setPrice(details.getUnitPrice());
            productInventoryBook.setProductModel(bizProduct.getModel());
            productInventoryBook.setTenantId(SecurityUtils.getTenantId());
            productInventoryBook.setProductId(bizProduct.getId());
            productInventoryBook.setRemark(bizInventoryOpening.getRemark());
            productInventoryBook.setOrderType("3");
            bizProductInventoryBookService.save(productInventoryBook);
        }
        return true;
    }

    @Override
    @Transactional(readOnly = false)
    public Boolean doAuditBizInventoryOpening(String id) {
        BizInventoryOpening bizInventoryOpening = super.get(id);
        bizInventoryOpening.setStatus(1);
        mapper.update(bizInventoryOpening);
        BizInventoryOpeningDetails paramDetail = new BizInventoryOpeningDetails();
        paramDetail.setOrderNo(bizInventoryOpening.getOrderNo());
        List<BizInventoryOpeningDetails> list = bizInventoryOpeningDetailsService.findList(paramDetail);
        for(BizInventoryOpeningDetails details:list) {
            BizProduct bizProduct = bizProductService.getBizProductByProductCode(details.getProductCode());
//            BizProductInventory bizProductInventory = new BizProductInventory();
//            bizProductInventory.setWarehouseId(bizInventoryOpening.getWarehouseId());
//            bizProductInventory.setSpaceId(details.getSpaceId());
//            bizProductInventory.setProductId(bizProduct.getId());
//            List<BizProductInventory> inventoryList = bizProductInventoryService.findList(bizProductInventory);
            BizProductInventory bizProductInventory = bizProductInventoryService.getByProductIdAndSpaceId(bizProduct.getId(),details.getSpaceId());
            //计算基础数量
            BigDecimal basicNumber = ConvertRatioNumberUnit.convertRatio(details.getProductNumber(), details.getUnit(), bizProduct);
            if(bizProductInventory!=null){
                BigDecimal number = bizProductInventory.getNumber() == null ? BigDecimal.ZERO : bizProductInventory.getNumber();
                BigDecimal productNumber = number.subtract(basicNumber);
                BigDecimal amount = bizProductInventory.getAmount()  == null ? BigDecimal.ZERO : bizProductInventory.getAmount();
                BigDecimal totalAmount = amount.subtract(details.getTotalAmount());
                bizProductInventory.setAmount(totalAmount);
                if (totalAmount.compareTo(BigDecimal.ZERO)>0){
                    bizProductInventory.setPrice(totalAmount.divide(productNumber,3,BigDecimal.ROUND_HALF_UP));
                }else {
                    bizProductInventory.setPrice(BigDecimal.ZERO);
                }
                bizProductInventory.setNumber(bizProductInventory.getNumber().subtract(basicNumber));
                bizProductInventory.setOpeningNumber(bizProductInventory.getOpeningNumber().subtract(basicNumber));
                bizProductInventory.setAssistNumberA(bizProductInventory.getNumber().multiply(bizProduct.getConvertRatioA()).setScale(3,BigDecimal.ROUND_HALF_UP));
                bizProductInventory.setAssistNumberB(bizProductInventory.getNumber().multiply(bizProduct.getConvertRatioB()).setScale(3,BigDecimal.ROUND_HALF_UP));
                bizProductInventoryService.update(bizProductInventory);
            }
            //删除产品库存台账
            bizProductInventoryBookService.deleteBizProductInventoryBookByOrderNumber(bizInventoryOpening.getOrderNo());
        }
        return true;
    }

}
